package com.esrc.web.service.impl;

import com.esrc.web.dto.RegionTreeDTO;
import com.esrc.web.entity.Region;
import com.esrc.web.mapper.RegionMapper;
import com.esrc.web.service.RegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: lx
 * @time: 2025/6/16
 */
@Service
public class ReginServiceImpl implements RegionService {
    @Autowired
    private RegionMapper regionMapper;

    @Override
    public List<RegionTreeDTO> getRegionTree() {
        // 查询所有地区（按parent_id排序）
        List<Region> regions = regionMapper.selectAllOrdered();

        Map<Long, RegionTreeDTO> nodeMap = new HashMap<>();
        Map<Long, List<RegionTreeDTO>> parentChildMap = new HashMap<>();

        regions.forEach(region -> {
            RegionTreeDTO node = new RegionTreeDTO(
                    region.getId(),
                    region.getParentId(),
                    region.getCode(),
                    region.getName()
            );
            nodeMap.put(region.getId(), node);
        });

        // 构建父子关系
        regions.forEach(region -> {
            Long parentId = region.getParentId();
            RegionTreeDTO node = nodeMap.get(region.getId());

            if (parentId != null && parentId != 0) {
                RegionTreeDTO parentNode = nodeMap.get(parentId);
                if (parentNode != null) {
                    parentNode.getChildren().add(node);
                }
            }
        });

        return regions.stream()
                .filter(region -> region.getParentId() == 0)
                .map(region -> nodeMap.get(region.getId()))
                .collect(Collectors.toList());
    }
}
